<template>
  <div class="timing-rule-table">
    <a-table :columns="columns" :data-source="_value" :pagination="false">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'time'">
          <a-time-picker
            v-model:value="record.time"
            valueFormat="HH:mm:ss"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          />
        </template>
        <template v-if="column.key === 'operate'">
          <a-button type="link" :disabled="_value.length <= 1">
            <template #icon><i class="iconfont icon-delete" @click="deleteTimeItemHandle(index)" /></template>
          </a-button>
        </template>
      </template>
    </a-table>
    <div :class="['add-item', { 'add-item-disabled': addTimeBtnDisabled }, 'inline-block']" @click="addTimeItemHandle">
      <i class="iconfont icon-add" />
      <span>新增时间</span>
    </div>
  </div>
</template>

<script lang="ts" setup name="TimingRuleTable">
import type { TimingRuleTableDataType } from './type'
import { computed, toRefs } from 'vue'

// props
type Props = { newValue: TimingRuleTableDataType }
const props = defineProps<Props>()
const { newValue } = toRefs(props)

// table
const columns = [
  {
    title: '时间',
    dataIndex: 'time'
  },
  {
    title: '操作',
    key: 'operate'
  }
]

// 最大个数
const MAX_NUMBER = 4

// 新增时间 btnDisabled
const addTimeBtnDisabled = computed(() => _value.value.length === MAX_NUMBER)

// v-model:newValue
const emit = defineEmits<{ (e: 'update:newValue', val: TimingRuleTableDataType): void }>()
const _value = computed({
  get: () => {
    return newValue.value
  },
  set: (val: TimingRuleTableDataType) => {
    emit('update:newValue', val)
  }
})

// operate
const addTimeItemHandle = () => {
  if (_value.value.length === MAX_NUMBER) return
  _value.value.push({ time: '00:00:00' })
}

const deleteTimeItemHandle = (index: number) => {
  _value.value = _value.value.filter((f, i) => i !== index)
}
</script>

<style lang="less" scoped>
.timing-rule-table {
  margin-top: 17px;

  .ant-picker {
    width: 240px;
  }

  .icon-delete {
    color: #fe4c4d;
    font-size: 20px;
    cursor: pointer;
  }
  .icon-add {
    font-size: 16px;
  }

  .add-item {
    margin-top: 8px;
    color: #0083ff;
    cursor: pointer;

    span {
      font-size: 14px;
    }
  }

  .add-item-disabled {
    color: #bfbfbf !important;
    cursor: not-allowed !important;
  }
}
</style>
